import request from "../../../utils/request"
import { Dispatch } from "redux"
import { rootState } from "../../../store"

const defaultState = {
	focused: false,
	mouseIn: false,
	list: [],
}

export enum IFocusActionType {
	FOCUS,
	BLUR,
	MOUSE_ENTER,
	MOUSE_LEAVE,
	GET_HOT_SEARCH,
}

export const getHotSearch = (dispatch: Dispatch, getState: () => rootState) => {
	if (getState().header.list.length) return
	request
		.get("/hotsearch")
		.then(res => {
			dispatch({ type: IFocusActionType.GET_HOT_SEARCH, payload: res.data["data"] })
		})
		.catch(err => {
			console.log("get hotsearch err: ", err)
		})
}

const reducer = (state = defaultState, action: { type: IFocusActionType; payload: any }) => {
	switch (action.type) {
		case IFocusActionType.FOCUS:
			return {
				focused: true,
				mouseIn: state.mouseIn,
				list: state.list,
			}
		case IFocusActionType.BLUR:
			return {
				focused: false,
				mouseIn: state.mouseIn,
				list: state.list,
			}
		case IFocusActionType.GET_HOT_SEARCH:
			return {
				focused: state.focused,
				mouseIn: false,
				list: JSON.parse(JSON.stringify([...state.list, ...action.payload])),
			}
		case IFocusActionType.MOUSE_ENTER:
			return {
				focused: state.focused,
				mouseIn: true,
				list: state.list,
			}
		case IFocusActionType.MOUSE_LEAVE:
			return {
				focused: state.focused,
				mouseIn: false,
				list: state.list,
			}
		default:
			return state
	}
}

export default reducer
